<template>
  <div class="import-container">
    <el-card>
      <!-- 标题 -->
      <h2>{{ title }}导入</h2>
      <el-alert
        title="每次导入仅可添加1000名员工,姓名、手机、入职时间、聘用形式为必填项"
        type="warning"
        show-icon
      />
      <UploadExcel :on-success="successHandler" />
    </el-card>
  </div>
</template>

<script>
// 导入接口
import { importEmployees } from '../../api/employees'
// 导入上传组件
import UploadExcel from '../../components/UploadExcel'
// 导入工具函数
import { formatExcelDate } from '../../utils/index'
export default {
  name: 'Import',
  components: {
    UploadExcel
  },
  computed: {
    title() {
      switch (this.$route.query.type) {
        case 'employee':
          return '员工'
        case 'departments':
          return '组织架构'
        default:
          return '你不对劲'
      }
    }
  },
  methods: {
    async successHandler(data) {
      // console.log('data:', data)
      // 基于现有数组 生成一个新的数组
      const newArr = data.results.map(v => {
        // return 要返回的每一项
        v.correctionTime = formatExcelDate(v.correctionTime, '/')
        v.timeOfEntry = formatExcelDate(v.timeOfEntry, '/')
        // 修改原对象
        return {
          ...v
        }
      })
      // console.log('newArr:', newArr)
      // 本地导入成功
      // 如果要调用不同的接口 结合type进行判断
      await importEmployees(newArr)
      this.$message.success('批量导入成功')
      this.$router.push({ path: '/employees' })
    }
  }
}
</script>

<style lang="scss">
.import-container {
  padding: 20px;
  .el-card {
    text-align: center;
  }
  .el-alert {
    margin-bottom: 20px;
  }
}
</style>
